/**
 * 保养计划 - 派工
 */

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import { euqApplicationName } from '../../config';

import {
    Card,
    Modal,
    Form,
    Row,
    Col,
    Input,
    Typography,
    TreeSelect,
    Select,
    Radio,
    Table,
    Button,
    message,
    Spin,
} from 'antd';

import { get, post } from '../../axios/http';

const { Title } = Typography;
const { TextArea } = Input;
const { Option } = Select;


/**
 * 保养部位表格
 */
function MaintenanceProgramDetail3Form1Table1({ data, onEvent }) {
    const handleActionClick = useCallback((e) => {
        e.preventDefault();
        switch (e.currentTarget.getAttribute('data-action')) {
            case 'delete': {
                onEvent && onEvent({ type: 'DELETE_ITEM', index: Number(e.currentTarget.getAttribute('data-index')) });
                break;
            }
        }
    }, [onEvent]);

    const tableColumns = [
        {
            title: '操作',
            render: (text, row, index) => {
                return (
                    <>
                        <a href="#" data-action="delete" data-index={index} onClick={handleActionClick}>删除</a>
                    </>
                );
            },
        },
        {
            title: '保养部位',
            dataIndex: 'positionName',
        },
        {
            title: '保养标准',
            dataIndex: 'maintainStandard',
        },
    ];

    return (
        <Table size="small" rowKey={(row, index) => index} dataSource={data} columns={tableColumns} pagination={false} />
    );
}

/**
 * 主表单
 */
const MaintenanceProgramDetail3Form1 = React.forwardRef(function MaintenanceProgramDetailForm1({ form, form: { getFieldDecorator, setFieldsValue, getFieldValue }, onEvent }, ref) {
    React.useImperativeHandle(ref, () => ({ form }));

    const [init, setInit] = useState(false);

    const [treeData1, setTreeData1] = useState([]);
    const [treeData2, setTreeData2] = useState([]);

    const [table1Data, setTable1Data] = useState([]);

    const treeData2Wrap = useMemo(() => {
        return treeData2.map(item =>
            <Option key={item.value} value={item.value}>{item.title}</Option>
        )
    }, [treeData2]);

    const handleTree2Change = useCallback((value) => {
        // console.log(value, treeData2);
        setFieldsValue({
            personNames: value.map(id => {
                return treeData2.filter(item => item.value === id)[0].title;
            }),
        });
    }, [treeData2]);

    // 保养部位表格
    const handleTable1Event = useCallback((e) => {
        switch (e.type) {
            case 'DELETE_ITEM': {
                setTable1Data(prev => {
                    const newData = [...prev];
                    newData.splice(e.index, 1);
                    return newData;
                });
                break;
            }
        }
    }, []);

    // 其它
    const handleSubmitClick = useCallback(() => {
        form.validateFields((err, values) => {
            if (err) {
                message.error('表单验证错误');
                return;
            }
            onEvent && onEvent({ type: 'FORM_SUBMIT', value: values });
        });
    }, [onEvent]);
    const handleCancelClick = useCallback(() => {
        onEvent && onEvent({ type: 'FORM_CANCEL' });
    }, [onEvent]);

    
    useEffect(() => {
        init && setFieldsValue({
            equipmentMaintainPositionAddDTOList: table1Data,
        });
    }, [table1Data]);

    useEffect(() => {
        console.log('init form:', form.getFieldsValue());
        setTable1Data(getFieldValue('equipmentMaintainPositionAddDTOList'));

        (async () => {
            try {
                const res1 = await get(euqApplicationName + '/currency/queryTeam');
                res1 && setTreeData1(res1.data.map(item => {
                    return {
                        title: item.name,
                        value: item.id,
                    };
                }));
            } catch (err) {}
        })();
        (async () => {
            try {
                const res2 = await get(euqApplicationName + '/equipmentMaintain/findUserOfMaintain');
                res2 && setTreeData2(res2.data.map(item => ({
                    title: item.userName,
                    value: item.id,
                })));
            } catch (err) { }
        })();

        setInit(true);
    }, []);

    return (
        <>
            <Form layout="horizontal" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
                <Title level={4}>设备信息</Title>
                <Row>
                    <Col span={6}>
                        <Form.Item label="设备编号">
                            {getFieldDecorator("equipmentCode")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="设备名称">
                            {getFieldDecorator("equipmentName")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="规格型号">
                            {getFieldDecorator("specsModel")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="设备类别">
                            {getFieldDecorator("typeName")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="使用部门">
                            {getFieldDecorator("equipmentDepart")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                {getFieldDecorator("equipmentId")(
                    <Input type="hidden" disabled />
                )}

                <Title level={4}>保养信息</Title>
                <Row>
                    <Col span={6}>
                        <Form.Item label="保养班组">
                            {getFieldDecorator("maintainTeamId")(
                                <TreeSelect treeData={treeData1} />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养负责人">
                            {getFieldDecorator("personId", {
                                initialValue: [],
                            })(
                                <Select mode="multiple" onChange={handleTree2Change}>
                                    {treeData2Wrap}
                                </Select>
                            )}
                        </Form.Item>
                        {getFieldDecorator('personNames', {
                            initialValue: [],
                        })(
                            <Input type="hidden" disabled />
                        )}
                    </Col>
                    <Col span={6}>
                        <Form.Item label="保养级别">
                            {getFieldDecorator("maintainLevel")(
                                <Input disabled />
                            )}
                        </Form.Item>
                        {getFieldDecorator("maintainLevelId")(
                            <Input type="hidden" disabled />
                        )}
                    </Col>
                    <Col span={6}>
                        <Form.Item label="提醒时间">
                            {getFieldDecorator("reminderTime")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="循环方式">
                            {getFieldDecorator("loopStyle")(
                                <Radio.Group disabled>
                                    <Radio value={0}>单次</Radio>
                                    <Radio value={1}>多次</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={4}>
                        <Form.Item label="循环周期" labelCol={{ span: 12 }} wrapperCol={{ span: 12 }}>
                            {getFieldDecorator("loopCycle")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={2}>
                        <Form.Item wrapperCol={{ span: 24 }}>
                            {getFieldDecorator("loopCycleUnit")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="计划保养时间">
                            {getFieldDecorator("maintainStartTime")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Form.Item label="至">
                            {getFieldDecorator("maintainEndTime")(
                                <Input disabled />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label="工作描述" labelCol={{ span: 2 }} wrapperCol={{ span: 22 }}>
                            {getFieldDecorator("description")(
                                <TextArea rows={4} disabled />
                            )}
                        </Form.Item>
                    </Col>
                </Row>
                
                <Title level={4} style={{ marginTop: 15 }}>保养部位</Title>
                <MaintenanceProgramDetail3Form1Table1 data={table1Data} onEvent={handleTable1Event} />
                {getFieldDecorator('equipmentMaintainPositionAddDTOList', {
                    initialValue: [],
                })(
                    <Input type="hidden" />
                )}

                {getFieldDecorator("id")(
                    <Input type="hidden" />
                )}

                <div style={{ marginTop: 20 }}>
                    <Button type="primary" style={{ marginRight: 5 }} onClick={handleSubmitClick}>保存</Button>
                    <Button onClick={handleCancelClick}>取消</Button>
                </div>
            </Form>
        </>
    )
});


/**
 * 主组件
 */
function MaintenanceProgramDetail3() {
    const { id } = useParams();
    const history = useHistory();

    const [isDataLoading, setIsDataLoading] = useState(true);
    const [formData, setFormData] = useState({});

    // 主表单
    const Form1Wrap = useMemo(() => {
        return Form.create({
            mapPropsToFields(props) {
                const { data } = props;
                return (data && data.id) ? {
                    id: Form.createFormField({ value: data.id }),
                    equipmentCode: Form.createFormField({ value: data.equipmentCode }),
                    equipmentName: Form.createFormField({ value: data.equipmentName }),
                    specsModel: Form.createFormField({ value: data.specsModel }),
                    typeName: Form.createFormField({ value: data.typeName }),
                    equipmentDepart: Form.createFormField({ value: data.equipmentDepart }),
                    equipmentId: Form.createFormField({ value: data.equipmentId }),
                    maintainTeamId: Form.createFormField({ value: data.maintainTeamId }),
                    personId: Form.createFormField({ value: data.personId != null ? data.personId.split(',').map(Number) : [] }),
                    personNames: Form.createFormField({ value: data.personNames != null ? data.personNames.split(',') : [] }),
                    maintainLevel: Form.createFormField({ value: data.maintainLevel }),
                    maintainLevelId: Form.createFormField({ value: data.maintainLevelId }),
                    reminderTime: Form.createFormField({ value: data.reminderTime }),
                    loopStyle: Form.createFormField({ value: data.loopStyle }),
                    loopCycle: Form.createFormField({ value: data.loopCycle }),
                    loopCycleUnit: Form.createFormField({ value: data.loopCycleUnit }),
                    maintainStartTime: Form.createFormField({ value: data.maintainStartTime }),
                    maintainEndTime: Form.createFormField({ value: data.maintainEndTime }),
                    description: Form.createFormField({ value: data.description }),
                    equipmentMaintainPositionAddDTOList: Form.createFormField({ value: data.equipmentMaintainPositionAddDTOList || [] }),
                } : {};
            }
        })(MaintenanceProgramDetail3Form1);
    }, [formData]);

    const handleForm1Event = useCallback((e) => {
        switch (e.type) {
            case 'FORM_SUBMIT': {
                // console.log('submit:', e.value);
                const reqData = {
                    ...e.value,
                    userId: Number(localStorage.getItem('userId')),
                    personId: e.value.personId.join(','),
                    personNames: e.value.personNames.join(','),
                };
                // console.log(reqData); return;
                (async () => {
                    try {
                        const res = await post(euqApplicationName + '/equipmentMaintainPlan/equipmentMaintainPlanDispatch', { data: reqData });
                        message.info('计划执行成功');
                        history.replace('/MaintenanceProgram');
                    } catch (err) {}
                })();
                break;
            }
            case 'FORM_CANCEL': {
                history.goBack();
                break;
            }
        }
    }, []);

    useEffect(() => {
        (async () => {
            try {
                const res = await get(euqApplicationName + '/equipmentMaintainPlan/findDispatchExecuteEquipmentMaintainPlan', { params: { planId: id } });
                if (res && res.data.length > 0) {
                    setFormData(res.data[0]);
                    setIsDataLoading(false);
                } else {
                    Modal.error({
                        title: '未找到保养计划',
                        onOk() {
                            history.goBack();
                        },
                    });
                }
            } catch (err) {}
        })();
    }, []);

    return (
        <>
            <h3>派工</h3>
            <Card size="small" style={{ position: 'relative' }}>
                <Form1Wrap data={formData} onEvent={handleForm1Event} />
                {isDataLoading && (
                    <div className="x-cover-loading2">
                        <Spin size="large" />
                    </div>
                )}
            </Card>
        </>
    );
}

export default MaintenanceProgramDetail3;
